package com.atguigu.tingshu.album.receiver;

import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class AlbumReceiver {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private TrackInfoService trackInfoService;

    @RabbitListener(bindings =@QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_TRACK, durable = "true"),
            value = @Queue(value = MqConst.QUEUE_TRACK_STAT_UPDATE, durable = "true"),
            key = MqConst.ROUTING_TRACK_STAT_UPDATE

    ))
    @SneakyThrows
    public void updateStat(TrackStatMqVo mqVo, Message message, Channel channel){
        if (mqVo != null) {
            log.info("[专辑服务]收到消息：{}", mqVo);
            //幂等性处理
            String redisKey = RedisConstant.BUSINESS_PREFIX + mqVo.getBusinessNo();
            Boolean flag = redisTemplate.opsForValue().setIfAbsent(redisKey, "1", 5, TimeUnit.MINUTES);
            if (flag){

                try {
                    //更新声音统计
                    trackInfoService.updateTrackStat(mqVo);

                }catch (Exception e){
                    log.error("[专辑服务]更新声音统计失败：{}", e.getMessage());
                    redisTemplate.delete(redisKey);
                    channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
                }
            }

        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}
